<template>

  <!--搜索面板-->
  <el-card v-show="showSearch">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-input size="default" v-model="query.searchVal" placeholder="请输入搜索内容..." clearable/>
      </el-col>
      <el-col :span="8">
        <el-date-picker
            v-model="query.searchDate"
            type="daterange"
            unlink-panels
            size="default"
            range-separator=":"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="shortcuts"
        />
      </el-col>
      <el-button size="default" type="success" :icon="Search" @click="initPage">搜索
      </el-button>
      <el-button size="default" type="primary" :icon="Refresh" @click="refresh">重置</el-button>
    </el-row>
  </el-card>

  <!--操作/表格面板-->
  <el-card>
    <!--操作-->
    <div class="operate">
      <el-row>
        <el-col :span="21">
          <el-button type="primary" :icon="Plus" @click="insertDialogVisible = true">新增</el-button>
          <el-button type="danger" :disabled="deleteDisabled" :icon="Delete" @click="handleBatchDelete">删除</el-button>
          <el-button type="warning" :icon="Download" @click="handleBatchExport">导出</el-button>
        </el-col>
        <el-col :span="3" class="operate-right">
          <el-button :icon="Search" @click.stop="showSearch=!showSearch"/>
          <el-button :icon="Refresh" @click.stop="initPage"/>
          <el-button :icon="Grid" @click="ElMessage.info('待开发...')"/>
        </el-col>
      </el-row>
    </div>
    <!--表格-->
    <el-table
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        :default-sort="{ prop: 'id', order: 'ascending'}"
        v-loading="loading"
    >
      <el-table-column type="selection" width="30"/>
      <el-table-column prop="id" label="ID" sortable/>
      <el-table-column prop="name" label="标签名"/>
      <el-table-column prop="alias" label="标签别名"/>
      <el-table-column prop="description" label="描述"/>
      <el-table-column prop="createTime" label="创建时间"/>
      <el-table-column prop="updateTime" label="修改时间"/>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button size="small" :icon="EditPen" type="primary" @click="handleEdit( scope.row)"/>
          <el-popconfirm
              title="确定删除该标签吗?"
              confirm-button-text="是"
              confirmButtonType="danger"
              cancel-button-text="否"
              cancelButtonType="default"
              :icon="InfoFilled"
              icon-color="red"
              @confirm="confirmDelete(scope.row.id)">
            <template #reference>
              <el-button size="small" :icon="Delete" type="danger"/>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <el-pagination
        v-model:currentPage="query.currentPage"
        v-model:page-size="query.pageSize"
        :page-sizes="[5,10,20,30,50]"
        :total="total"
        :small="true"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, prev, pager, next , sizes"
        style="margin-top: 15px;margin-right:30px;display: flex;align-items: center;justify-content: right"
    />
  </el-card>

  <!--新增对话框-->
  <el-dialog v-model="insertDialogVisible" title="新增标签" width="30%">
    <el-form :model="insertLabelData">
      <el-form-item label="标签名称">
        <el-input v-model="insertLabelData.name"/>
      </el-form-item>
      <el-form-item label="标签别名">
        <el-input v-model="insertLabelData.alias"/>
      </el-form-item>
      <el-form-item label="标签描述">
        <el-input v-model="insertLabelData.description"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="insertDialogVisible = false">返回</el-button>
      <el-button type="primary" @click="confirmInsert">确认</el-button>
    </template>
  </el-dialog>

  <!--编辑对话框-->
  <el-dialog v-model="editorDialogVisible" title="新增标签" width="30%">
    <el-form :model="editorLabelData">
      <el-form-item label="标签名称">
        <el-input v-model="editorLabelData.name"/>
      </el-form-item>
      <el-form-item label="标签别名">
        <el-input v-model="editorLabelData.alias"/>
      </el-form-item>
      <el-form-item label="标签描述">
        <el-input v-model="editorLabelData.description"/>
      </el-form-item>
      <el-form-item label="创建时间">
        <span>{{ editorLabelData.createTime }}</span>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="editorDialogVisible = false">返回</el-button>
      <el-button type="primary" @click="confirmUpdate">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {onMounted, ref} from "vue";
import {queryData, Label} from "../../api/label/types";
import {Search, Plus, Grid, Refresh, EditPen, Delete, Download, InfoFilled} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {addLabel, deleteBatchLabel, deleteLabel, getLabelByPage, updateLabel} from "../../api/label/label";

const showSearch = ref<boolean>(true)
const insertDialogVisible = ref<boolean>(false)
const editorDialogVisible = ref<boolean>(false)
const total = ref<number>(0)
const loading = ref(false)
const labelIds = ref<number[]>([])
let tableData = ref<Label[]>([]);


const query = ref<queryData>({
  currentPage: 1,
  pageSize: 5,
  searchDate: '',
  searchVal: ''
})


// 初始化页面
const initPage = async () => {
  const {data} = await getLabelByPage(query.value)
  if (data.data) {
    tableData.value = data.data.list;
    total.value = data.data.total
  }
}

// 重置处理
const refresh = () => {
  query.value.searchDate = ''
  query.value.searchVal = ''
  initPage()
}


// 新增处理
let insertLabelData = ref<Label>({
  name: '',
  alias: '',
  description: ''
})
const confirmInsert = async () => {
  const {data} = await addLabel(insertLabelData.value)
  if (data.code === 200) {
    ElMessage.success('添加成功')
    insertDialogVisible.value = false
    insertLabelData.value = {name: '', alias: '', description: ''}
    // location.reload()
    await initPage()
    return
  }
  ElMessage.error('添加失败')
}


// 多选处理
const deleteDisabled = ref<boolean>(true)
const handleSelectionChange = (labels: Label[]) => {
  labelIds.value = []
  if (labels.length === 0) {
    deleteDisabled.value = true// 禁用删除键
    return
  }
  labels.forEach(item => labelIds.value.push(item.id as number))
  deleteDisabled.value = false// 启用删除键
}


// 批量删除处理
const handleBatchDelete = () => {
  ElMessageBox.confirm(
      '是否删除选择的数据?', '警告',
      {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning',
        showClose: false
      }
  ).then(async () => {
    const {data} = await deleteBatchLabel(labelIds.value)
    if (data.code === 200) {
      ElMessage.success('删除成功')
      editorDialogVisible.value = false
      await initPage()
      return
    }
    ElMessage.error('删除失败')
  })
}


// 批量导出处理
const handleBatchExport = () => {
  ElMessage.info("待开发...")
}


// 表格编辑处理
let editorLabelData = ref<Label>({
  name: '',
  alias: '',
  description: ''
})
const handleEdit = (row: Label) => {
  editorDialogVisible.value = true
  editorLabelData.value = JSON.parse(JSON.stringify(row))// 避免引用传递  做一次拷贝
}
const confirmUpdate = async () => {
  const {data} = await updateLabel(editorLabelData.value)
  if (data.code === 200) {
    ElMessage.success('修改成功')
    editorDialogVisible.value = false
    await initPage()
    return
  }
  ElMessage.error('修改失败')
}


// 表格删除处理
const confirmDelete = async (id: number) => {
  const {data} = await deleteLabel(id)
  if (data.code === 200) {
    ElMessage.success('删除成功')
    await initPage()
    return
  }
  ElMessage.error('删除失败')
}


// 分页相关处理
const handleSizeChange = (size: number) => {
  query.value.pageSize = size
  query.value.currentPage = 1
  initPage()
}
const handleCurrentChange = (page: number) => {
  query.value.currentPage = page
  initPage()
}


// 日期时间选择
const shortcuts = [
  {
    text: '今天',
    value: [new Date(), new Date()],
  },
  {
    text: '今年',
    value: () => {
      const start = new Date(new Date().getFullYear(), 0)
      const end = new Date()
      return [start, end]
    },
  },
  {
    text: '半年前',
    value: () => {
      const start = new Date()
      const end = new Date()
      start.setMonth(start.getMonth() - 6)
      return [start, end]
    },
  },
]


onMounted(() => initPage())
</script>

<style scoped lang="scss">
.operate {
  .operate-right {
    display: flex;
    justify-content: left;
    align-items: center;
    margin-bottom: 20px;

    button {
      margin: 0;

      &:nth-child(1) {;
        border-bottom-right-radius: 0;
        border-top-right-radius: 0;
      }

      &:nth-child(2) {
        border-radius: 0;
      }

      &:nth-child(3) {
        border-bottom-left-radius: 0;
        border-top-left-radius: 0;
      }
    }

  }
}
</style>